import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getUserData } from "./mockData";


interface IUserInfo {
  id: string
  name: string
  age: number
}

interface IInitState {
  loading: boolean
  login: boolean
  userInfo: IUserInfo | null
}

const initState: IInitState = {
  loading: false,
  login: false,
  userInfo: null
}

const userSlice = createSlice({
  name: 'userInfo',
  initialState: {
    value: initState
  },
  reducers: {
    logout(state) {
      state.value.userInfo = null
    }
  },
  extraReducers: builder => {
    builder
      .addCase(getUserInfoAction.pending, (...rest) => {
        // loading
        console.log('loading', rest)
        // state.value.loading = true
      })
      .addCase(getUserInfoAction.fulfilled, (...rest) => {
        // success
        console.log('success', rest)
        // state.value.loading = false
        // state.value.login = true
        // state.value.userInfo
      })
      .addCase(getUserInfoAction.rejected, (...rest) => {
        // failed
        console.log('failed', rest)
        // state.value.loading = false
        // state.value.login = false
      })
  }
})

export const getUserInfoAction = createAsyncThunk(
  'userInfo',
  async () => {
    // 获取用户信息，return data
    // async function
    let res = await getUserData()
    return res
  }
)

export const { logout } = userSlice.actions
export default userSlice.reducer



